import { AutoComplete, Button, Form, Input, message, Radio, Select, Spin, Tabs } from 'antd';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import request from '@/utils/request';
import DynamicHttpHeaders from '@/components/DynamicHttpHeaders';

const { TabPane } = Tabs;

const SmallFormItemLayout = {
  labelCol: { span: 3 },
  wrapperCol: { span: 9 },
};

function Main({ versionId, form, readOnly = false, onCancel }) {
  const { getFieldDecorator, getFieldValue, setFieldsValue, validateFields } = form;

  const requestBodyFormat = getFieldValue('requestBodyFormat') || 'JSON';
  const responseBodyFormat = getFieldValue('responseBodyFormat') || 'JSON';

  const [loading, setLoading] = useState(true);

  const [httpHeaders, setHttpHeaders] = useState([]);
  const headersRef = useRef(null);

  useEffect(() => {
    request
      .get(`/httpDataSource/queryVersionData?versionId=${versionId}`)
      .then(data => {
        if (data) {
          const responseHeaders = data.responseHeaders ? JSON.parse(data.responseHeaders) : [];
          setFieldsValue({
            ...data,
            responseStatus: `${data.responseStatus}`,
          });
          setHttpHeaders(responseHeaders);
        }
      })
      .finally(() => setLoading(false));
  }, [setFieldsValue, versionId]);

  /**
   * 提交表单
   */
  const handleSubmit = useCallback(() => {
    validateFields((err, fieldsValue) => {
      if (!err) {
        setLoading(true);
        request
          .post('/httpDataSource/saveVersionData', {
            data: {
              ...fieldsValue,
              responseHeaders: httpHeaders ? JSON.stringify(httpHeaders) : '[]',
              httpDataSourceVersionId: versionId,
            },
          })
          .then(() => {
            message.success('保存成功');
            onCancel();
          })
          .finally(() => {
            setLoading(false);
          });
      }
    });
  }, [httpHeaders, onCancel, validateFields, versionId]);

  function renderFooter() {
    if (readOnly) {
      return null;
    }
    return (
      <div className="modal-footer">
        <div className="pull-right">
          <Button style={{ marginRight: 8 }} onClick={onCancel}>
            取消
          </Button>
          <Button type="primary" onClick={handleSubmit} loading={loading}>
            保存
          </Button>
        </div>
      </div>
    );
  }

  return (
    <>
      <Spin spinning={loading}>
        <Form layout="horizontal">
          <div style={{ display: 'flex' }}>
            <Form.Item>{getFieldDecorator('configId')(<Input hidden />)}</Form.Item>
            <Form.Item style={{ flex: 'none' }}>
              {getFieldDecorator('requestMethod', {
                initialValue: 'POST',
                rules: [
                  {
                    required: true,
                  },
                ],
              })(
                <Select disabled={readOnly} placeholder="--请选择--" style={{ width: '90px' }}>
                  <Select.Option key="POST" value="POST">
                    POST
                  </Select.Option>
                  <Select.Option key="GET" value="GET">
                    GET
                  </Select.Option>
                  <Select.Option key="PUT" value="PUT">
                    PUT
                  </Select.Option>
                  <Select.Option key="PATCH" value="PATCH">
                    PATCH
                  </Select.Option>
                  <Select.Option key="DELETE" value="DELETE">
                    DELETE
                  </Select.Option>
                </Select>
              )}
            </Form.Item>
            <Form.Item style={{ flex: 1 }}>
              {getFieldDecorator('requestUrl', {
                rules: [
                  {
                    required: true,
                    message: '请求地址不能为空',
                  },
                  {
                    pattern: /^\/.*$/,
                    message: '请求地址必须以"/"开头',
                  },
                ],
              })(<Input disabled={readOnly} placeholder='接口路径，"/"起始' allowClear />)}
            </Form.Item>
          </div>
          <div className="ant-detail-title">请求参数</div>
          <Tabs defaultActiveKey="body">
            <TabPane tab="Body" key="body">
              <Form.Item
                label="格式"
                {...{
                  labelCol: { span: 3 },
                  wrapperCol: { span: 9 },
                }}
              >
                {getFieldDecorator('requestBodyFormat', {
                  initialValue: 'JSON',
                  rules: [
                    {
                      required: true,
                      message: '格式不能为空',
                    },
                  ],
                })(
                  <Radio.Group disabled={readOnly}>
                    <Radio value="JSON">JSON</Radio>
                    <Radio value="XML">XML</Radio>
                    <Radio value="NONE">普通文本</Radio>
                    {/* <Radio value="BINARY">二进制</Radio> */}
                  </Radio.Group>
                )}
              </Form.Item>
              <Form.Item label="编码" {...SmallFormItemLayout}>
                {getFieldDecorator('requestEncoding', {
                  initialValue: 'UTF-8',
                  rules: [
                    {
                      required: true,
                      message: '编码不能为空',
                    },
                  ],
                })(
                  <AutoComplete
                    disabled={readOnly}
                    dataSource={['UTF-8', 'GBK']}
                    placeholder="请输入"
                  />
                )}
              </Form.Item>
            </TabPane>
          </Tabs>
          <div className="ant-detail-title">响应参数</div>
          <Tabs defaultActiveKey="body">
            <TabPane tab="Body" key="body">
              <Form.Item
                label="格式"
                {...{
                  labelCol: { span: 3 },
                  wrapperCol: { span: 9 },
                }}
              >
                {getFieldDecorator('responseBodyFormat', {
                  initialValue: 'JSON',
                  rules: [
                    {
                      required: true,
                      message: '格式不能为空',
                    },
                  ],
                })(
                  <Radio.Group disabled={readOnly}>
                    <Radio value="JSON">JSON</Radio>
                    <Radio value="XML">XML</Radio>
                    <Radio value="NONE">普通文本</Radio>
                    {/* <Radio value="BINARY">二进制</Radio> */}
                  </Radio.Group>
                )}
              </Form.Item>
              <Form.Item label="编码" {...SmallFormItemLayout}>
                {getFieldDecorator('responseEncoding', {
                  initialValue: 'UTF-8',
                  rules: [
                    {
                      required: true,
                      message: '编码不能为空',
                    },
                  ],
                })(
                  <AutoComplete
                    disabled={readOnly}
                    dataSource={['UTF-8', 'GBK']}
                    placeholder="请输入"
                  />
                )}
              </Form.Item>
            </TabPane>
            <TabPane tab="Header" key="header">
              <DynamicHttpHeaders ref={headersRef} value={httpHeaders} onChange={setHttpHeaders} />
            </TabPane>
            <TabPane tab="Status" key="status">
              <Form.Item label="响应码" {...SmallFormItemLayout}>
                {getFieldDecorator(`responseStatus`, {
                  initialValue: '200',
                  rules: [
                    {
                      required: true,
                      message: '响应码不能为空',
                    },
                    {
                      len: 3,
                      message: '响应码长度不为3',
                    },
                  ],
                })(<Input disabled={readOnly} placeholder="请输入" />)}
              </Form.Item>
            </TabPane>
          </Tabs>
          {/* <div className="ant-detail-title">高级选项</div>
        <Tabs defaultActiveKey="timeout">
          <TabPane tab="超时" key="timeout">
            <Row>
              <Col span={12}>
                <Form.Item label="超时时间" {...FormItemLayout}>
                  {getFieldDecorator('timeout', {
                    initialValue: '5',
                  })(<Input disabled={readOnly} placeholder="请输入" suffix="秒" />)}
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="重试间隔" {...FormItemLayout}>
                  {getFieldDecorator('retryIntervals', {
                    initialValue: '1 3 5',
                  })(<Input disabled={readOnly} placeholder="请输入" suffix="秒" />)}
                </Form.Item>
              </Col>
            </Row>
          </TabPane>
          <TabPane tab="Mock" key="mock">
            <Row>
              <Col span={12}>
                <Form.Item label="开启" {...FormItemLayout}>
                  {getFieldDecorator('isMock', {
                    initialValue: false,
                  })(<Switch disabled={readOnly} />)}
                </Form.Item>
              </Col>
            </Row>
            {getFieldValue('isMock') ? (
              <Row>
                <Col span={24}>
                  <Form.Item
                    label="模拟响应"
                    {...{
                      labelCol: { span: 3 },
                      wrapperCol: { span: 21 },
                    }}
                  >
                    {getFieldDecorator('mockResponse')(
                      <TextArea
                        disabled={readOnly}
                        autoSize={{ minRows: 10, maxRows: 10 }}
                        placeholder="请输入"
                      />
                    )}
                  </Form.Item>
                </Col>
              </Row>
            ) : null}
          </TabPane>
        </Tabs> */}
        </Form>
      </Spin>
      {renderFooter()}
    </>
  );
}

export default Form.create()(Main);
